﻿'''
Author: thinktanker thinktanker@163.com
Date: 2023-08-14 09:44:37
LastEditors: thinktanker thinktanker@163.com
LastEditTime: 2025-05-06 14:30:45
FilePath: 
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import serial
import serial.tools.list_ports
import time
import zlib


def compress_string(string: str):
    # compressed_data = bz2.compress(bytes(string, 'utf-8'))
    compressed_data = zlib.compress(bytes(string, 'utf-8'))
    return compressed_data


def getCOMport(tag=''):
    '''
    找到单片机的端口，返回COM值
    '''
    # 获取所有串口设备实例。
    # 如果没找到串口设备，则输出：“无串口设备。”
    # 如果找到串口设备，则依次输出每个设备对应的串口号和描述信息。
    ports_list = list(serial.tools.list_ports.comports())
    if len(ports_list) <= 0:
        print("无串口设备。")
    else:
        print("有可用串口")
        for comport in ports_list:
            # print(list(comport)[0], '       ', list(comport)[1])
            # print(list(comport))
            if tag in list(comport)[1]:
                # print(list(comport)[0])
                return list(comport)[0]
    return list(comport)


def openCOM(comport="", baudrate=115200, sendContent=b""):
    ser = serial.Serial(comport, baudrate,
                        timeout=0.01)  # 打开COM17，将波特率配置为115200，其余参数使用默认值
    if ser.isOpen():  # 判断串口是否成功打开
        # print(ser.name, "打开串口成功。")  # 输出串口号
        print("发送的信息：", len(sendContent))
        print(sendContent)
        # sendContent = sendContent.encode('utf-8')
        # print(sendContent)
        print("发送结果：", ser.write(sendContent))
        ser.flush()
        # # 分割发送120个字节一个
        # for i in range(0, len(sendContent), 120):
        #     print("发送长度：", ser.write(sendContent[i:i + 120]))
        #     # time.sleep(1)
        #     ser.flush()
        #     recvData = ""
        recvData = ""
        while True:
            com_input = ser.read(1024)
            if com_input:
                recvData = com_input.decode("utf-8", errors='ignore')
            else:
                break
        ser.close()
        print("收到的信息：")
        if recvData:
            print(recvData)
    else:
        print("打开串口失败。")


def sendCom(
    comport="",
    baudrate=115200,
    sendContent=[],
):
    '''
    向4g模块发送数据
    '''
    ser = serial.Serial(comport, baudrate,
                        timeout=0.01)  # 打开COM17，将波特率配置为115200，其余参数使用默认值
    if sendContent == []:
        return
    # sendContent = [str(s).encode('utf-8') for s in sendContent]
    init_orders = [
        b'AT+QICSGP=1,1,"","",""\r\n',  #  设置APN
        b"AT$HTTPOPEN\r\n",  # 打开HTTP连接
        b"AT$HTTPPARA=https://16gs832674.oicp.vip/sim,443,1,0\r\n",  # 设置HTTP连接       
    ]

    if ser.isOpen():  # 判断串口是否成功打开
        for cmd in init_orders:
            ser.write(cmd)
            ser.flush()
            recvData = ""
            while True:
                com_input = ser.read(1024)
                recvData += com_input.decode("utf-8", errors='ignore')
                if not com_input:
                    # 短暂等待，再次尝试读取，确保数据完全接收
                    time.sleep(0.5)
                    com_input = ser.read(1024)
                    recvData += com_input.decode("utf-8", errors='ignore')
                    print("收到的信息：", recvData)
                    if "OK" in recvData:
                        break
        total_length = 0
        for sendlist in sendContent:

            # sendbytes = bytes(str(sendlist), "utf-8")
            sendbytes = str(sendlist) + "SIM"
            list_length = len(sendbytes)
            # sendbytes = compress_string(str(sendlist))
            # list_length = len(sendbytes)
            total_length += list_length
            # send_orders = [
            #     b"AT$HTTPRQH=Content-Length," +
            #     bytes(str(list_length), 'utf-8') + b"\r\n",  #  设置数据长度
            #     b"AT$HTTPDATAEX=" + bytes(str(list_length), 'utf-8') + b",\"" +
            #     sendbytes + b"\"\r\n",  # 发送数据
            #     b"AT$HTTPACTION=3\r\n"  #  执行HTTP请求
            # ]
            send_orders = [
                f"AT$HTTPRQH=Content-Length,{list_length}\r\n",  #  设置数据长度
                f"AT$HTTPDATAEX={list_length},\"{sendbytes}\"\r\n",  # 发送数据       
                "AT$HTTPACTION=3\r\n"  #   执行HTTP请求
            ]
            send_orders = [cmd.encode('utf-8') for cmd in send_orders]

            for cmd in send_orders:
                recvData = ""
                retry = True
                while retry:
                    print("发送命令：", cmd)
                    ser.write(cmd)  #
                    ser.flush()
                    while True:
                        com_input = ser.read(1024)
                        recvData += com_input.decode("utf-8", errors='ignore')
                        if not com_input:
                            # 短暂等待，再次尝试读取，确保数据完全接收
                            time.sleep(1)
                            com_input = ser.read(1024)
                            print("收到的信息：", recvData)
                            if "OK" in recvData:
                                retry = False
                                break
                            elif "ERROR" in recvData:
                                print("发送失败！")
                                retry = False
                                break
                            elif "AT$HTTPACTION=3" in recvData:
                                retry = False
                                time.sleep(2)
                                break
                            else:
                                retry = True
                                time.sleep(5)
                                break
        print("总字节数：", total_length)
        close_order = b"AT$HTTPCLOSE\r\n"
        recvData = ""
        ser.write(close_order)
        ser.flush()
        while True:
            com_input = ser.read(1024)
            if com_input:
                recvData += com_input.decode("utf-8", errors='ignore')
            else:
                # 短暂等待，再次尝试读取，确保数据完全接收
                time.sleep(0.5)
                com_input = ser.read(1024)
                recvData += com_input.decode("utf-8", errors='ignore')
                print("收到的信息：", recvData)
                if "OK" in recvData:
                    break
        ser.close()

    else:
        print("打开串口失败。")
    pass


if __name__ == "__main__":
    # sendContent = "上游水位：18.46m下游进水池水位：15.76m下游清污机前水位：15.82m瞬时流量：0.00ms平均流速：0.00m/s35kV进线开关柜Ta4.3AP257kQ47kVarcOSp0.98所变进线开关柜Ia0.5APQk1Q0kVarcoSP1.00主变进线开关柜Ia4.4P262kQ50kVarcOSp0.98母线电压Uab6.5kVUbc6.6kVUca6.6kVTMY-100*106kVI段母线电压Uab0.0kVUbc0.0kVUca0.0kV6016kV进线开关柜Ia21.0P249kQ24kVarCOS0.99631站变高压开关柜la21.21252Q28kVarCOS0.99621发电机Ia0.0P0.0Q0.0kVarUL0.0IL0.0COS0.00622电动机130.0P0.0kVQ0.0kVarUL0.0IL0.0COS1.006111#机组1a0.0AP0.0kvQ0.0kVarUL0.00VIL0.00ACOS1.006122#机组la0.0AP0.0kQ0.0kVarUL0.00VIL0.00ACOS1.006133#机组1a0.0AP0.0kwQ0.0kVarUL0.00VIL0.00ACOS1.006144#机组Ia0.0A0.0kv0.0kVarUL0.00VIL0.00ACOS1.00615二站发电开关柜Ia0.1P0kQ0kVarCOS1.00 "
    # openCOM(comport="COM3", sendContent=sendContent)
    sendContent = [
        [
            'ZJX', '37.47', '0.0', '1.0', '2.0', '112.0', '22.0', '0.98',
            '6.42', '9.0', '37.96', '102.0', '1.0', '1.0', '8.0', '105.0',
            '2.0', '1.0', '0.0', '0.0', '0.0', '37.99', '0.0', '0.0', '1.0',
            '0.0', '6.44', '6.48', '0.0', '0.0', '0.0', '0.0', '2.0', '0.0',
            '1.0', '112.0', '27.0', '0.98', '0.0', '0.0', '1', '1', '0', '0',
            '0', '0', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0',
            '0', '0', '1', '1', '1', '1', '1', 1728960801
        ],
        [
            '6', '45.1', '48.1', '45.4', '58.1', '49.9', '55.6', '50.4',
            '62.4', 1728961326
        ],
        [
            '7', '0.0', '25.0', '23.0', '25.0', '17.0', '21.0', '19.0',
            '21.0', '2014.04', '9191.61', '2047.18', '23.0', 1728961333
        ], ['DD', '0', '1',
            '0', '0', 1728961339], ['FD', '0', '0', '0', '1', 1728961346],
        [
            'JZ0', '21.16', '21.16', '15.99', '15.99', '16.04', '16.04', '0.0',
            '0.0', 1728961353
        ],
        [
            'JZ1', '-3.98', '0.0', '0.0', '0.0', '1.0', '0.0', '0.0', '0.0',
            '0.0', '21.0', '23.6', '23.7', '26.0', '23.6', '22.1', '24.0',
            '23.8', '24.1', '23.9', '24.0', '23.8', '23.0', '23.7', '23.8',
            '23.9', '0.3', '0.5', '1.0', '1.0', '7.0', '7.0', '2.0', '3.0',
            '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '1.66', '0.0',
            '0', '0', '1', '0', '1', '1', '0', '0', '1', '1', '1', '0', '0',
            1728961360
        ],
        [
            'JZ2', '-18.27', '0.0', '0.0', '0.0', '1.0', '0.0', '0.0', '0.0',
            '0.0', '23.0', '23.5', '23.3', '19.0', '23.7', '23.3', '23.7',
            '24.0', '23.6', '23.6', '24.0', '23.8', '24.0', '23.7', '23.5',
            '23.5', '1.7', '1.3', '1.0', '2.0', '2.0', '4.0', '0.0', '0.0',
            '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0',
            '1', '0', '1', '0', '1', '1', '1', '0', '0', 1728961367
        ],
        [
            'JZ3', '-17.03', '0.0', '0.0', '0.0', '1.0', '0.0', '0.0', '0.0',
            '0.0', '0.0', '23.6', '23.3', '27.0', '23.5', '23.5', '23.9',
            '23.9', '23.8', '23.7', '23.0', '24.0', '24.0', '23.7', '23.6',
            '23.9', '0.8', '1.3', '4.0', '2.0', '11.0', '12.0', '0.0', '2.0',
            '2.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0',
            '1', '0', '1', '0', '1', '1', '1', '0', '0', 1728961374
        ],
        [
            'JZ4', '-3.95', '0.0', '0.0', '0.0', '1.0', '0.0', '0.0', '0.0',
            '0.0', '23.0', '23.7', '23.4', '-15.0', '24.0', '23.2', '23.7',
            '19.5', '24.0', '24.0', '25.0', '23.9', '23.0', '24.0', '24.1',
            '24.0', '0.8', '1.1', '2.0', '2.0', '2.0', '2.0', '0.0', '2.0',
            '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '1.76', '0.0',
            '1', '0', '0', '1', '0', '1', '1', '1', '0', '0', 1728961381
        ],
        [
            'SHUI', '0.0', '0.3', '24.8', '0.1', '40.0', '21.46', '20.66',
            '20.73', '20.19', '22.0', '24.0', '24.0', '46.5', '1', '0', '1',
            '0', '0', '0', '0', '0', '0', '1', '0', '1', '1', '0', '0', '0',
            '0', '1', '1', '0', '0', 1728961389
        ]
    ]
    test_com = getCOMport('USB-Enhanced-SERIAL CH343')
    if type(test_com) == list:
        test_com = test_com[0]
    # sendCom(comport=test_com[0], sendContent=sendContent)
    openCOM(comport=test_com,
            sendContent=compress_string(str(sendContent)) + b'END')
